//
//  AppDelegate.m
//  家校互通
//
//  Created by 姬鑫宇 on 15/4/10.
//  Copyright (c) 2015年 姬鑫宇. All rights reserved.
//

#import "AppDelegate.h"
#import "APService.h"
#import "ViewController.h"
#import "PortraitNavViewController.h"
#import <AlipaySDK/AlipaySDK.h>
#import "WXApi.h"
#import "UserInfoViewController.h"
#import "CoModel.h"
#import "MsgPlaySound.h"

extern NSString *const kReciveSendMsg = @"kReciveSendMsg";     // 收到文本聊天
extern NSString *const kReciveSendImg = @"kReciveSendImg";     // 收到图片聊天
extern NSString *const kReciveCreateClazzChart = @"kReciveCreateClazzChart";  // 收到创建聊天室
extern NSString *const kReciveDeleteClazzChart = @"kReciveDeleteClazzChart";  // 收到删除聊天室
extern NSString *const kReciveOutClazzChart = @"kReciveOutClazzChart";        // 收到退出聊天室
extern NSString *const kReciveLeaveApply = @"kReciveLeaveApply";              // 收到创建假条
extern NSString *const kReciveDeleteLeaveApply = @"kReciveDeleteLeaveApply";  // 收到删除假条
extern NSString *const kReciveNewsList = @"kReciveNewsList";              // 更新消息列表


extern NSString *const kReloadNewsList = @"kReloadNewsList"; // 刷新个人信息
extern NSString *const kReloadMyInfo = @"kReloadMyInfo";    // 重新获取消息列表

@interface AppDelegate ()

@end
BMKMapManager* _mapManager;
@implementation AppDelegate


//收到消息
- (void)networkDidReceiveMessage:(NSNotification *)notification {
    NSDictionary * userInfo = [notification userInfo];
    NSString *content = [userInfo valueForKey:@"content"];
    NSDictionary *dict = [[NSDictionary alloc]initWithDictionary:[DSFUserInfo dictionaryWithJsonString:content]];
    NSLog(@"%@",dict);
    //震动
    MsgPlaySound *playSound = [[MsgPlaySound alloc] initSystemShake];
    [playSound play];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:kReciveNewsList object:notification userInfo:dict];
    //判断消息类型并推送
    NSInteger type = [[dict objectForKey:@"type"] integerValue];
    
    NSDictionary *dic = [dict objectForKey:@"data"];
    NSInteger chart_type = [[dic objectForKey:@"type"] integerValue];
    
    switch (type) {
        case 1://收到创建请假条、聊天室
            [[NSNotificationCenter defaultCenter] postNotificationName:kReloadNewsList object:notification userInfo:dict];
            
            if (chart_type == 1 || chart_type == 2)
                [[NSNotificationCenter defaultCenter] postNotificationName:kReciveCreateClazzChart object:notification userInfo:dict];
            else
                [[NSNotificationCenter defaultCenter] postNotificationName:kReciveLeaveApply object:notification userInfo:dict];
            break;
        case 2://收到删除请假条、聊天室
            if (chart_type == 1 || chart_type == 2)
                [[NSNotificationCenter defaultCenter] postNotificationName:kReciveDeleteClazzChart object:notification userInfo:dict];
            else
                [[NSNotificationCenter defaultCenter] postNotificationName:kReciveDeleteLeaveApply object:notification userInfo:dict];
            break;
        case 3://收到聊天消息
            [[NSNotificationCenter defaultCenter] postNotificationName:kReciveNewsList object:notification userInfo:dict];

            if (chart_type == 1) {//收到文本推送
                [[NSNotificationCenter defaultCenter] postNotificationName:kReciveSendMsg object:notification userInfo:dict];
            }else//收到图片推送
                [[NSNotificationCenter defaultCenter] postNotificationName:kReciveSendImg object:notification userInfo:dict];

            break;
        case 4://收到退出聊天室
            [[NSNotificationCenter defaultCenter] postNotificationName:kReciveOutClazzChart object:notification userInfo:dict];
            break;
        default:
            break;
    }
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    _mapManager = [[BMKMapManager alloc]init];
    BOOL ret = [_mapManager start:@"GGRq6oSFpu77NMYp6WawoXV7" generalDelegate:self];
    
    if (!ret) {
        NSLog(@"manager start failed!");
    }
    
//极光推送
    [APService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
                                                   UIRemoteNotificationTypeSound |
                                                   UIRemoteNotificationTypeAlert)
                                       categories:nil];
    [APService setupWithOption:launchOptions];
    
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter addObserver:self selector:@selector(networkDidReceiveMessage:) name:kJPFNetworkDidReceiveMessageNotification object:nil];
    
//页面跳转
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
//    self.window.backgroundColor = [UIColor whiteColor];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *string = [defaults objectForKey:@"notificationR"];
    NSLog(@"notificationR = %@",string);
    
    if (![NSString isBlankString:[defaults objectForKey:@"username"]]) {
        NSInteger userType = [[defaults objectForKey:@"userType"] intValue];
        if (userType == 1) {
            [DSFUserInfo shareUserInstance].isTeachLogin = YES;
        }else if (userType == 2){
            [DSFUserInfo shareUserInstance].isTeachLogin = NO;
        }
        //登陆成功后页面跳转
        UIStoryboard * storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        UserInfoViewController *vc = [storyboard  instantiateViewControllerWithIdentifier:@"UserInfoViewController"];
        PortraitNavViewController *nav = [[PortraitNavViewController alloc] initWithRootViewController:vc];
        
        self.window.rootViewController = nav;
      
    }else{
        UIStoryboard * storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        ViewController *vc = [storyboard  instantiateViewControllerWithIdentifier:@"ViewController"];
        PortraitNavViewController *nav = [[PortraitNavViewController alloc] initWithRootViewController:vc];
        
        self.window.rootViewController = nav;
    }
        
    [self.window makeKeyAndVisible];
    return YES;
}


- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    NSLog(@"%@", [NSString stringWithFormat:@"Device Token: %@", deviceToken]);
    [APService registerDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application
didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}

#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_7_1
- (void)application:(UIApplication *)application
didRegisterUserNotificationSettings:
(UIUserNotificationSettings *)notificationSettings {
    NSLog(@"handleActionWithIdentifier1");
}

// Called when your app has been activated by the user selecting an action from
// a local notification.
// A nil action identifier indicates the default action.
// You should call the completion handler as soon as you've finished handling
// the action.
- (void)application:(UIApplication *)application
handleActionWithIdentifier:(NSString *)identifier
forLocalNotification:(UILocalNotification *)notification
  completionHandler:(void (^)())completionHandler {
    NSLog(@"handleActionWithIdentifier2");
}

// Called when your app has been activated by the user selecting an action from
// a remote notification.
// A nil action identifier indicates the default action.
// You should call the completion handler as soon as you've finished handling
// the action.
- (void)application:(UIApplication *)application
handleActionWithIdentifier:(NSString *)identifier
forRemoteNotification:(NSDictionary *)userInfo
  completionHandler:(void (^)())completionHandler {
    NSLog(@"handleActionWithIdentifier3");
}
#endif


- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
    // Required
    [APService handleRemoteNotification:userInfo];
    NSLog(@"收到通知:%@", [self logDic:userInfo]);
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:[self logDic:userInfo] forKey:@"notificationR"];
    [defaults synchronize];
}

- (NSString *)logDic:(NSDictionary *)dic {
    if (![dic count]) {
        return nil;
    }
    NSString *tempStr1 =
    [[dic description] stringByReplacingOccurrencesOfString:@"\\u"
                                                 withString:@"\\U"];
    NSString *tempStr2 =
    [tempStr1 stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
    NSString *tempStr3 =
    [[@"\"" stringByAppendingString:tempStr2] stringByAppendingString:@"\""];
    NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
    NSString *str =
    [NSPropertyListSerialization propertyListFromData:tempData
                                     mutabilityOption:NSPropertyListImmutable
                                               format:NULL
                                     errorDescription:NULL];
    return str;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    [BMKMapView willBackGround];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    // IOS 7 Support Required
    [APService handleRemoteNotification:userInfo];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:[self logDic:userInfo] forKey:@"notificationR"];
    [defaults synchronize];
    NSLog(@"收到通知:%@", [self logDic:userInfo]);
}

- (void)application:(UIApplication *)application
didReceiveLocalNotification:(UILocalNotification *)notification {
    [APService showLocalNotificationAtFront:notification identifierKey:nil];
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    [application setApplicationIconBadgeNumber:0];
    [application cancelAllLocalNotifications];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    [BMKMapView didForeGround];
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    //如果极简开发包不可用,会跳转支付宝钱包进行支付,需要将支付宝钱包的支付结果回传给开 发包
    if ([url.host isEqualToString:@"safepay"]) {
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url
                                                  standbyCallback:^(NSDictionary *resultDic) {
                                                      NSLog(@"result = %@",resultDic);
                                                  }]; }
    if ([url.host isEqualToString:@"platformapi"]){//支付宝钱包快登授权返回 authCode
        [[AlipaySDK defaultService] processAuthResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
        }];
    }
    return YES;

}

//- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
//{
//    return  [WXApi handleOpenURL:url delegate:self];
//}

#pragma mark -
#pragma mark Memory management

- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
    /*
     Free up as much memory as possible by purging cached data objects that can be recreated (or reloaded from disk) later.
     */
}

- (void)onGetNetworkState:(int)iError
{
    if (0 == iError) {
        NSLog(@"联网成功");
    }
    else{
        NSLog(@"onGetNetworkState %d",iError);
    }
    
}

- (void)onGetPermissionState:(int)iError
{
    if (0 == iError) {
        NSLog(@"授权成功");
    }
    else {
        NSLog(@"onGetPermissionState %d",iError);
    }
}


@end
